package com.ndood.api.domain.router.receive.v1.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ndood.api.base.constaints.ApiCode;
import com.ndood.api.base.exception.ApiException;
import com.ndood.api.domain.risk.receive.v1.service.RiskRecPlatformOfflineAlif2fService;
import com.ndood.api.domain.support.merchant.entity.dto.SupportMchRecChannelDto;
import com.ndood.api.domain.support.merchant.service.SupportMchRecChannelService;
import com.ndood.api.domain.support.staff.entity.dto.SupportStaffDto;

/**
 * 平台支付-线下渠道路由-支付宝当面付路由 渠道路由的职责是根据支付类型选择对应的渠道
 */
@Service
public class RouteRecPlatformOfflineAlif2fService {

	@Autowired
	private SupportMchRecChannelService supportMchRecChannelService;

	@Autowired
	private RiskRecPlatformOfflineAlif2fService riskRecPlatformAlif2fService;

	/**
	 * 1 渠道路由
	 */
	public SupportMchRecChannelDto route(String productNo, String amount, SupportStaffDto staff)
			throws ApiException {

		// Step1: 获取所有支付渠道信息
		List<SupportMchRecChannelDto> channels = supportMchRecChannelService.getMerchantReceiveChannel(staff.getMchId(),
				productNo);
		if (channels.isEmpty()) {
			throw new ApiException(ApiCode.ERR_SERVER, "没有可用的收款渠道");
		}

		// Step2: 智能渠道路由
		SupportMchRecChannelDto dest = null; // 目标渠道
		for (SupportMchRecChannelDto channel : channels) {
			// 1 风控
			boolean riskThrough = riskRecPlatformAlif2fService.checkRisk(amount, staff, productNo, channel);
			// 2 路由选择获取最佳渠道
			if (!riskThrough) {
				continue;
			}
			dest = channel;
			break;
		}

		// Step3: 返回结果
		if (dest == null) {
			throw new ApiException(ApiCode.ERR_SERVER, "没有可用的收款支付渠道");
		}
		return dest;
	}

}
